package com.android.test.activity;

import java.lang.reflect.Method;
import java.util.ArrayList;
import com.android.test.R;
import com.android.test.model.BaiduSearchListener;
import com.android.test.model.IconPair;
import com.android.test.model.OrgInfo;
import com.android.test.model.OrgListAdapter;
import com.android.test.util.Constants;
import com.android.test.util.DeviceUtil;
import com.android.test.util.IconCache;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.MKSearch;
import com.baidu.mapapi.MapActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AbsListView.OnScrollListener;

public final class OrgListActivity extends MapActivity implements
		AdapterView.OnItemClickListener {
	private final static String TAG = OrgListActivity.class.getSimpleName();
	private final static int DIALOG_PROGRESS_SEARCH_NEARBY = 1;
	private final static int DIALOG_PROGRESS_SEARCH_LOCATION = 2;
	private final static int SEARCH_COUNT_MAX = 3;
	private final static int TIME_OUT_COUNT = 15000;
	private static final int MSG_FORCE_DECODE_IMAGE = 200;
	private static final int MSG_DOWNLOAD_STATE_CHANGE = 201;
	private static final int MSG_REQUEST_SEARCH = MSG_DOWNLOAD_STATE_CHANGE + 1;
	private static final int MSG_SEARCH_FAILED = MSG_REQUEST_SEARCH + 1;
	private static final int MSG_SHOW_ADDRESS_RESULT = MSG_SEARCH_FAILED + 1;
	private static final int MSG_REMOVE_PROGRESS_DIALOG = MSG_SHOW_ADDRESS_RESULT + 1;
	// private static final int SORT_ITEM_NORMAL = 300;
	// private static final int SORT_ITEM_DISTAN = 301;
	// private static final int SORT_ITEM_RECOMM = 302;
	// private static final int COUNT_PER_TIME = 7;
	// private final int MAX_PENDING_SIZE = 7;
	// private final int CACHE_ID_THUMBNAIL = 99;
	// private final int CACHE_ID_ORG_LIST = 107;
	// private int startIndex;
	private boolean mReachEnd;
	// private View mProgressIndicator;
	private ListView mListView;
	// private View mHeaderView;
	// private View mFooterView;
	private OrgListAdapter mOrgListAdapter;
	// private boolean showTopApp;
	private String mFromPage;
	private boolean inflatingAppList;
	// private boolean mContainsHeader;
	// private boolean mContainsFooter;
	// private String mType;
	public int mCategoryId;
	public String mCategoryLabel;
	public int mRankingType;
	public int mPeriodType;
	private int mListOrder;

	/*
	 * 0 加载未完成 1 加载完成 2 不显示
	 */
	// private boolean loadedList;
	private boolean mScrolling = false; // Indicate if the view is scrolling now
	private boolean mDone;
	private Thread mDecodeThread = null;
	private final ArrayList<WorkItem> mQueue = new ArrayList<WorkItem>();
	private final ArrayList<Integer> mPendingRequest = new ArrayList<Integer>();
	// for BAIDU map engine
	private BMapManager mapManager = null;
	private MKSearch mMKSearch = null;
	private BaiduSearchListener mSearchListener = null;
	private OrgInfo mClickedOrgInfo = null;
	private CountDownTimer mTimer = null;
	private int mSearchCount = 0;
	private int mCurDialogId = -1;
	private boolean mSearchFinished = true;
	private boolean bRegisted = false;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_org_list);
		/*
		 * if (savedInstanceState != null) { showTopApp =
		 * savedInstanceState.getBoolean("showTopApp"); mFromPage =
		 * savedInstanceState.getString("fromPage"); mContainsHeader =
		 * savedInstanceState.getBoolean("header"); mType =
		 * savedInstanceState.getString("type"); mCategoryId =
		 * savedInstanceState.getInt("_id"); mCategoryLabel =
		 * savedInstanceState.getString("category_label"); mRankingType =
		 * savedInstanceState.getInt("ranking_type"); mListOrder =
		 * savedInstanceState.getInt("list_order"); mPeriodType =
		 * savedInstanceState.getInt("period"); } else { Intent intent =
		 * getIntent(); showTopApp = intent.getBooleanExtra("showTopApp",
		 * false); mFromPage = intent.getStringExtra("fromPage");
		 * mContainsHeader = intent.getBooleanExtra("header", false); mType =
		 * intent.getStringExtra("type"); mCategoryId =
		 * intent.getIntExtra("_id", -1); mCategoryLabel =
		 * intent.getStringExtra("category_label"); mRankingType =
		 * intent.getIntExtra("ranking_type", -1); mListOrder =
		 * intent.getIntExtra("list_order", SORT_ITEM_NORMAL); mPeriodType =
		 * intent.getIntExtra("period", 0); }
		 */
		initBaiduMap();
		initView();
		initData();
	}

	private void initBaiduMap() {
		mapManager = new BMapManager(this);
		// the BAIDU map key
		if (!mapManager.init(Constants.KEY_MAP_BAIDU, null)) {
			Log.e(TAG, "mapManager.init failed");
			return;
		}
		if (!super.initMapActivity(mapManager)) {
			Log.e(TAG, "initMapActivity failed");
			return;
		}
		if (mapManager != null) {
			mapManager.start();
		}

		mSearchListener = new BaiduSearchListener(this);
		if (mMKSearch == null) {
			mMKSearch = new MKSearch();
			if (mMKSearch == null) {
				Log.e(TAG, "new MKSearch failed");
				return;
			}
			boolean isInitOk = mMKSearch.init(mapManager, mSearchListener);
			if (!isInitOk) {
				Log.e(TAG, "mMKSearch.init failed");
				return;
			}
		}
		// MyLocationOverlay loc = new MyLocationOverlay(this, (MapView)
		// findViewById(R.id.map_View));
		// GeoPoint point = loc.getMyLocation();
		// Log.e(TAG,"My Location latitude = "+point.getLatitudeE6()+", longitude="+point.getLongitudeE6());
		// if (mapManager != null) {
		// mLocationManager = mapManager.getLocationManager();
		// if (mLocationManager != null){
		// mLocationManager.requestLocationUpdates(OrgListActivity.this);
		// }
		// mapManager.start();
		// }
		// else{
		// Log.e(TAG, "mapManager is null");
		// }
		// if (mLotInt != 0 || mLatInt != 0){
		// dismissDialog(DIALOG_INIT_PROGRESS_BAR);
		// }
		// }
	}

	private void searchByOrgInfo(OrgInfo info) {
		if (mSearchCount >= SEARCH_COUNT_MAX) {
			searchFinished();
			mHandler.sendEmptyMessage(MSG_SEARCH_FAILED);
			Log.e(TAG, "Search failed");
			return;
		}
		if (null == mSearchListener) {
			mSearchListener = new BaiduSearchListener(OrgListActivity.this);
		}
		mSearchListener.setKeyWords(info.shortName);
		searchByGeoPoint(info.mGpoint);
	}

	private void searchByGeoPoint(GeoPoint point) {
		int result = -1;
		try {
			if (mMKSearch == null) {
				mMKSearch = new MKSearch();
				if (mMKSearch == null) {
					Log.e(TAG, "new MKSearch failed");
					return;
				}
				boolean isInitOk = mMKSearch.init(mapManager, mSearchListener);
				if (!isInitOk) {
					Log.e(TAG, "mMKSearch.init failed");
					return;
				}
			}
			if (mSearchFinished) {
				mSearchFinished = !mSearchFinished;
				mCurDialogId = DIALOG_PROGRESS_SEARCH_LOCATION;
				showDialog(mCurDialogId);
			}
			result = mMKSearch.reverseGeocode(point);
			mSearchCount++;
			Log.e(TAG, "mSearchCount=" + mSearchCount);
			startSearchTimer();
		} catch (Exception e) {
			e.printStackTrace();
			Log.e(TAG, "Search has failed");
		}
		if (result == -1) {
			Log.e(TAG, "reverseGeocode Search has failed");
		}
	}

	private void startSearchTimer() {
		mTimer = new CountDownTimer(TIME_OUT_COUNT, 1000) {
			public void onTick(long millisUntilFinished) {
			}

			public void onFinish() {
				// search timeout we kill it
				Log.e(TAG, "Search timeout");
				mHandler.sendEmptyMessage(MSG_SEARCH_FAILED);
			}
		}.start();
	}

	private void resetSearchTimer() {
		if (mTimer != null) {
			mTimer.cancel();
			mTimer = null;
		}
	}

	private void searchFinished() {
		Log.e(TAG, "search finished");
		resetSearch();
		resetSearchTimer();
	}

	@Override
	public void onResume() {
		registReceivers();
		if (mapManager != null) {
			mapManager.start();
			Log.e(TAG, "start mapmanager onResume");
		}
		if (!mSearchFinished) {
			resetSearch();
			Log.e(TAG, "Reset search environment");
		}
		if (mOrgListAdapter != null) {
			mOrgListAdapter.notifyDataSetChanged();
		}
		super.onResume();
	}

	private void resetSearch() {
		mSearchCount = 0;
		mSearchFinished = true;
		mClickedOrgInfo = null;
		Log.e(TAG, "Reset mClickedOrgInfo = null");
		mHandler.sendEmptyMessage(MSG_REMOVE_PROGRESS_DIALOG);
	}

	@Override
	protected void onStop() {
		unRegistReceivers();
		if (!mSearchFinished) {
			resetSearchTimer();
			Log.e(TAG, "cancel search timer onStop");
		}
		if (mapManager != null) {
			mapManager.stop();
			Log.e(TAG, "stop mapmanager onStop");
		}
		synchronized (mQueue) {
			mDone = true;
			mQueue.clear();
			mQueue.notifyAll();
		}
		if (mDecodeThread != null) {
			try {
				Thread t = mDecodeThread;
				t.join();
				mDecodeThread = null;
			} catch (InterruptedException ex) {
				// so now what?
			}
		}
		super.onStop();
	}

	@Override
	public void onDestroy() {
		unRegistReceivers();
		if (mapManager != null) {
			mapManager.destroy();
			mapManager = null;
		}
		if (!mSearchFinished) {
			resetSearchTimer();
			Log.e(TAG, "cancel search timer onDestroy");
		}
		super.onDestroy();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

		/*
		 * outState.putBoolean("showTopApp", showTopApp);
		 * outState.putString("fromPage", mFromPage);
		 * outState.putBoolean("header", mContainsHeader);
		 * outState.putString("type", mType); outState.putInt("_id",
		 * mCategoryId); outState.putString("category_label", mCategoryLabel);
		 * outState.putInt("ranking_type", mRankingType);
		 * outState.putInt("list_order", mListOrder); outState.putInt("period",
		 * mPeriodType);
		 */

	}

	@Override
	public boolean onSearchRequested() {
		return false;
	}

	protected void initView() {
		/* mProgressIndicator = findViewById(R.id.fullscreen_loading_indicator); */

		mListView = (ListView) findViewById(R.id.listView);

		if (DeviceUtil.getSDKVersionInt() > DeviceUtil.SDK_VERSION_1_6) {
			try {
				Method method = mListView.getClass().getMethod(
						"setScrollbarFadingEnabled",
						new Class[] { boolean.class });
				method.invoke(mListView, new Object[] { true });
			} catch (Throwable e) {
				e.printStackTrace();
			}
		}

		/*
		 * if (mContainsFooter) { mFooterView =
		 * LayoutInflater.from(this).inflate( R.layout.asset_list_footer, null);
		 * mListView.addFooterView(mFooterView); }
		 * 
		 * if (mContainsHeader) { mHeaderView =
		 * LayoutInflater.from(this).inflate( R.layout.relative_app_header,
		 * null); mHeaderView.setEnabled(false);
		 * mListView.addHeaderView(mHeaderView, null, false); }
		 */

		mListView.setOnItemClickListener(this);
		mListView.setOnScrollListener(scrollListener);
	}

	protected void initData() {
		inflateOrgList();
	}

	private void registReceivers() {
		if (!bRegisted) {
			IntentFilter filter = new IntentFilter();
			filter.addAction(Constants.ACTION_ADDR_RESULT);
			registerReceiver(mReceiver, filter);
			bRegisted = !bRegisted;
			Log.e(TAG, "Regist recevier");
		}
	}

	private void unRegistReceivers() {
		if (bRegisted) {
			unregisterReceiver(mReceiver);
			bRegisted = !bRegisted;
			Log.e(TAG, "Unregist recevier");
		}
	}

	private BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().endsWith(Constants.ACTION_ADDR_RESULT)) {
				Log.e(TAG, "Receive Search result coming");
				if (mSearchFinished) {
					Log.e(TAG, "Search has finished");
					return;
				}
				final String strExtra = intent
						.getStringExtra(Constants.KEY_ADDR_RESULT);
				if (TextUtils.isEmpty(strExtra)) {
					mHandler.sendEmptyMessage(MSG_REQUEST_SEARCH);
				} else {
					Message msg = new Message();
					msg.obj = strExtra;
					msg.what = MSG_SHOW_ADDRESS_RESULT;
					mHandler.sendMessage(msg);
				}
			}
		}
	};

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_REQUEST_SEARCH: {
					if (mClickedOrgInfo != null) {
						searchByOrgInfo(mClickedOrgInfo);
					}
				}
				break;
			case MSG_SEARCH_FAILED: {
					searchFinished();
					dialogShowMessage(R.string.title_tip_dialog, getResources()
							.getString(R.string.msg_search_failed));
				}
				break;
			case MSG_REMOVE_PROGRESS_DIALOG: {
					if (mSearchFinished) {
						removeDialog(mCurDialogId);
						mCurDialogId = -1;
					}
				}
				break;
			case MSG_SHOW_ADDRESS_RESULT: {
					if (msg.obj != null) {
						dialogShowSearchResult((String) msg.obj, mClickedOrgInfo);
						searchFinished();
					} else {
						mHandler.sendEmptyMessage(MSG_REQUEST_SEARCH);
					}
				}
				break;
			case MSG_DOWNLOAD_STATE_CHANGE:
				if (mOrgListAdapter != null) {
					if (mScrolling == false) {
						mOrgListAdapter.notifyDataSetChanged();
					} else {
						removeMessages(MSG_DOWNLOAD_STATE_CHANGE);
						sendMessageDelayed(
								obtainMessage(MSG_DOWNLOAD_STATE_CHANGE), 300);
					}
				}
				break;
			case MSG_FORCE_DECODE_IMAGE:
				if (mScrolling == false) {
					synchronized (mQueue) {
						if (mQueue != null) {
							mQueue.notifyAll();
						}
					}
				} else {
					removeMessages(MSG_FORCE_DECODE_IMAGE);
					sendMessageDelayed(obtainMessage(MSG_FORCE_DECODE_IMAGE),
							300);
				}
				break;
			}
		}
	};

	private void dialogShowSearchResult(String msg, final OrgInfo info) {
		new AlertDialog.Builder(OrgListActivity.this)
			.setTitle(R.string.msg_address_detail)
			.setMessage(msg)
			.setPositiveButton(R.string.msg_see, new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Intent intent = new Intent();
					intent.setClass(OrgListActivity.this,
							OrgDetailActivity.class);
					intent.putExtra("_id", info._id);
					intent.putExtra("title", info.shortName);
					intent.putExtra("promotionId", info.promotionId);
					startActivity(intent);
					dialog.dismiss();
				}
			})
			.setNegativeButton(R.string.text_abort, new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			}).create().show();
	}

	private void dialogShowMessage(int title, String msg) {
		new AlertDialog.Builder(OrgListActivity.this)
			.setTitle(R.string.title_tip_dialog).setMessage(msg)
			.setPositiveButton(R.string.ok, new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			}).create().show();
	}

	/***********************************************************
	 * 
	 * Called when the user call showDialog
	 * 
	 * @param
	 * 
	 * @return
	 * 
	 **********************************************************/
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_PROGRESS_SEARCH_NEARBY: {
			// create progress bar dialog
			ProgressDialog dialog = new ProgressDialog(this);
			dialog.setTitle(R.string.msg_wait);
			dialog.setMessage(getResources().getString(
					R.string.msg_search_nearby));
			dialog.setIndeterminate(false);
			return dialog;
		}
		case DIALOG_PROGRESS_SEARCH_LOCATION: {
			// create progress bar dialog
			final ProgressDialog dialog = new ProgressDialog(this);
			dialog.setTitle(R.string.msg_wait);
			dialog.setMessage(getResources().getString(
					R.string.msg_search_location));
			dialog.setIndeterminate(false);
			dialog.setCancelable(true);
			return dialog;
		}
		}
		return null;
	}

	private void processPendingRequest() {
		int size = mPendingRequest.size();
		if (size == 0) {
			return;
		}
		for (int i = 0; i < size; i++) {
			/*
			 * mHttpService.getOrgIcon(CACHE_ID_THUMBNAIL,
			 * mPendingRequest.get(i), mHandler);
			 */
		}
		mPendingRequest.clear();
	}

	private void inflateOrgList() {
		this.processHttpResponse(null);
		if (mReachEnd) {
			return;
		}
		if (!inflatingAppList) {
			inflatingAppList = true;

			/*
			 * mHttpService.getOrgList(mCategoryId, startIndex, COUNT_PER_TIME,
			 * 0, CACHE_ID_APP_LIST, mHandler);
			 */

		}
	}

	// google map 查询结果
	// 莞城区金牛路24号, 东莞市, 广东省 (阳光喔作文培训) @23.037465,113.753355
	// 上海市徐汇区五原路71号, (昂立少儿教育基地（五原总校）) @31.213194,121.448042
	// 百度地图查询结果
	// 地址：合群一马路111号越和海印苑商务中心1楼AA18 阳光喔作文培训
	// 电话：(020)83780405
	// 坐标：113.295258,23.126162
	// 昂立少儿教育中学生精品学堂
	// 地址：平凉路1730号
	// 电话：(021)65184827
	// 坐标：121.548396,31.273637
	//百度GeoPoint(纬度，经度)；google与之相反
	/*GeoPoint	public GeoPoint(int latitudeE6,int longitudeE6)
	用给定的经度和纬度构造一个GeoPoint，单位微度 (度 * 1E6)。
	参数：
	latitudeE6 - 该点的纬度，单位微度 (度 * 1E6)。为保持Mercator投影精确度，其取值范围是[-80*1E6,80*1E6]。
	longitudeE6 - 该点的经度，单位微度 (度 * 1E6)。可被规范化到(-180*1E6,180*1E6]。*/
	private ArrayList<OrgInfo> fakeOrgList() {
		ArrayList<OrgInfo> OrgList = new ArrayList<OrgInfo>();
		OrgInfo ob = new OrgInfo();
		ob.shortName = "阳光喔作文培训";
		ob.distance = "3.4km";
		ob.rating = 4.5f;
		ob.mGpoint = new GeoPoint(23126155, 113295252);//反查后的结果
		OrgList.add(ob);

		ob = new OrgInfo();
		ob.shortName = "昂立少儿教育";
		ob.distance = "2.1km";
		ob.rating = 4.5f;
		ob.mGpoint = new GeoPoint(31273629, 121548389);//反查后的结果
		OrgList.add(ob);

		return OrgList;
	}

	protected void processHttpResponse(Message msg) {
		ArrayList<OrgInfo> OrgList = new ArrayList<OrgInfo>();
		OrgList = fakeOrgList();
		if (mOrgListAdapter == null) {
			mOrgListAdapter = new OrgListAdapter(this, mListOrder);
			mListView.setAdapter(mOrgListAdapter);
		}
		Log.e("zzy", "size=" + OrgList.size());
		if (OrgList != null) {
			int size = OrgList.size();
			// Performance tuning,disable auto refresh
			mOrgListAdapter.setNotifyOnChange(false);
			for (int i = 0; i < size; i++) {
				mOrgListAdapter.add(OrgList.get(i));
				Log.e("zzy", "add");
			}
			mOrgListAdapter.setNotifyOnChange(true);
			mOrgListAdapter.notifyDataSetChanged();
		}
	}

	/*
	 * @Override protected void processHttpResponse(Message msg) { QueuedRequest
	 * qr = (QueuedRequest) msg.obj; switch (qr.requestId) { case
	 * CACHE_ID_APP_LIST: case CACHE_ID_DOWNLOAD_LIST: case
	 * CACHE_ID_RANKING_LIST: case CACHE_ID_SEARCH_APP_LIST: case
	 * CACHE_ID_APP_RELATIVE_LIST: // Log.d(TAG, "qr.requestId:" + qr.requestId
	 * + // "=========qr.result: " + qr.result); ArrayList<Asset> assets = null;
	 * if (qr.requestId == CACHE_ID_SEARCH_APP_LIST) { String searchResult =
	 * (String) qr.result; Object[] objects;
	 * 
	 * // 20110915 ltc FIX 搜索框 输入 pname: / pnames: / pub: + ... // 后点搜索导致的Crash
	 * if (mSearchType == Constants.SEARCH_TYPE_BY_KEYWORDS) { objects =
	 * mHttpService.getSearchListForKeywordsFromJson( this, searchResult);
	 * 
	 * if (objects != null && objects.length == 2) { mNextIndexStart = (Integer)
	 * objects[0]; assets = (ArrayList<Asset>) objects[1]; } } else { assets =
	 * (ArrayList<Asset>) mHttpService .getSearchListFromJson(this,
	 * searchResult); } // end 20110915
	 * 
	 * } else if (qr.requestId == CACHE_ID_DOWNLOAD_LIST) { assets =
	 * mHttpService.getDownloadListFromJson(this, (String) qr.result); } else {
	 * assets = mHttpService.getAppListFromJson(this, (String) qr.result); }
	 * 
	 * if (mAppListAdapter == null) { mAppListAdapter = new
	 * AdapterListApp(ActivityListApp.this, assets, mListOrder);
	 * mListView.setAdapter(mAppListAdapter); } else if (assets != null) { int
	 * size = assets.size(); // Performance tuning,disable auto refresh
	 * mAppListAdapter.setNotifyOnChange(false); for (int i = 0; i < size; i++)
	 * { mAppListAdapter.add(assets.get(i)); }
	 * mAppListAdapter.setNotifyOnChange(true);
	 * mAppListAdapter.notifyDataSetChanged(); }
	 * 
	 * if (assets != null) { startIndex += assets.size(); }
	 * 
	 * if (assets == null || assets.size() == 0 || assets.size() <
	 * COUNT_PER_TIME) { mReachEnd = true;
	 * mListView.removeFooterView(mFooterView); } if
	 * (mListView.getAdapter().isEmpty()) {
	 * mEmptyView.setVisibility(View.VISIBLE); }
	 * 
	 * if (showTopApp) { loadedList = true; if (loadedBanner == 1) {
	 * mProgressIndicator.setVisibility(View.GONE);
	 * mListView.setVisibility(View.VISIBLE); } else if (loadedBanner == 2) {
	 * try { mListView.removeHeaderView(mBannerArea); } catch (Exception e) {
	 * e.printStackTrace(); } mProgressIndicator.setVisibility(View.GONE);
	 * mListView.setVisibility(View.VISIBLE); } } else {
	 * mProgressIndicator.setVisibility(View.GONE);
	 * mListView.setVisibility(View.VISIBLE); }
	 * 
	 * inflatingAppList = false; break; case CACHE_ID_TOP_APP_DETAIL:
	 * mBannerList = mHttpService.getAssetObjectWithBannerFromJson(this,
	 * (String) qr.result); if (mBannerList != null && mBannerList.size() > 0) {
	 * mBannerApdapter = new BannerAdapter(this);
	 * mBannerArea.setAdapter(mBannerApdapter);
	 * mBannerArea.setOnItemClickListener(new BannerClickListener());
	 * mBannerArea .setSelection((int) (System.currentTimeMillis() % 10000));
	 * mBannerArea.setVisibility(View.VISIBLE); mBannerScrollHandler = new
	 * BannerScrollHandler(); mBannerScrollHandler.sendEmptyMessageDelayed(0,
	 * bannerScrollSpeed); loadedBanner = 1; } else { loadedBanner = 2; }
	 * 
	 * if (loadedList) { mProgressIndicator.setVisibility(View.GONE);
	 * mListView.setVisibility(View.VISIBLE); } break; case CACHE_ID_THUMBNAIL:
	 * // byte[] thumbData = ((ByteBuffer) qr.result).array(); // Bitmap
	 * thumbBitmap = BitmapFactory.decodeByteArray(thumbData, 0, //
	 * thumbData.length); // if (thumbBitmap != null) { // Drawable icon = new
	 * BitmapDrawable(thumbBitmap); //
	 * IconCache.getInstance().put(qr.applicationId, icon); // if
	 * (mAppListAdapter != null) { // mAppListAdapter.notifyDataSetChanged(); //
	 * } // } handleThumbnail(((ByteBuffer) qr.result).array(),
	 * qr.applicationId, null); break; case CACHE_ID_BANNER_IMAGE: byte[]
	 * bannerData = ((ByteBuffer) qr.result).array(); Bitmap bannerBitmap =
	 * BitmapFactory.decodeByteArray(bannerData, 0, bannerData.length); if
	 * (bannerBitmap != null) { Drawable icon = new
	 * BitmapDrawable(bannerBitmap); IconCache.getInstance().put("banner_" +
	 * qr.applicationId, icon); if (mBannerApdapter != null) {
	 * mBannerApdapter.notifyDataSetChanged(); } } break; } }
	 */

	private void handleThumbnail(byte[] thumbnail, int appId, String header) {
		if (thumbnail == null) {
			return;
		}
		if (mDecodeThread == null) {// start worker thread here
			start();
		}
		synchronized (mQueue) {
			// int mPendingNum = mQueue.size();
			WorkItem w = new WorkItem(thumbnail, appId, header);
			mQueue.add(w);
			if (!mScrolling) { // Not scrolling,fire it.
				mQueue.notifyAll();
			} else {// set a delayed message
				mHandler.sendMessageDelayed(
						mHandler.obtainMessage(MSG_FORCE_DECODE_IMAGE), 500);

			}
		}
	}

	private void start() {
		if (mDecodeThread != null) {
			return;
		}
		mDone = false;
		Thread t = new Thread(new WorkerThread());
		t.setName("image-decoder");
		mDecodeThread = t;
		t.start();
	}

	private static class WorkItem {
		byte[] mImage;
		int mAppID;
		String mHeader;

		WorkItem(byte[] image, int id, String header) {
			mImage = image;
			mAppID = id;
			mHeader = header;
		}
	}

	private class WorkerThread implements Runnable {
		public void run() {
			while (true) {
				WorkItem workItem = null;
				synchronized (mQueue) {
					if (mDone) {
						break;
					}
					if (!mQueue.isEmpty()) {
						workItem = mQueue.remove(0);
					} else {
						try {
							mQueue.wait();
						} catch (InterruptedException ex) {
							// ignore the exception
						}
						continue;
					}
					DecodeImages(workItem.mImage, workItem.mAppID,
							workItem.mHeader);
				}
			}
		}
	}

	private void DecodeImages(byte[] thumbData, int applicationId, String header) {
		Bitmap thumbBitmap = BitmapFactory.decodeByteArray(thumbData, 0,
				thumbData.length);
		if (thumbBitmap != null) {
			Drawable icon = new BitmapDrawable(thumbBitmap);
			if (header != null) {
				IconCache.getInstance().put(header + applicationId, icon);
			} else {
				IconCache.getInstance().put(applicationId, icon);
			}
		}
		System.gc();
		mHandler.removeMessages(MSG_DOWNLOAD_STATE_CHANGE);
		mHandler.sendMessageDelayed(
				mHandler.obtainMessage(MSG_DOWNLOAD_STATE_CHANGE), 100);
	}

	/*
	 * @Override protected void processHttpError(Message msg) { inflatingAppList
	 * = false; super.processHttpError(msg); }
	 */

	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (mClickedOrgInfo == null) {
			final OrgInfo item = (OrgInfo) parent.getItemAtPosition(position);
			if (item == null) {
				return;
			}
			mClickedOrgInfo = item;
			Log.e(TAG, "mClickedOrgInfo = " + mClickedOrgInfo);
			mHandler.sendEmptyMessage(MSG_REQUEST_SEARCH);
		}
	}

	public String getFromPage() {
		return mFromPage;
	}

	private void addThumbnailRequest(final int applicationId) {

		/*
		 * if(mScrolling == false){ mHttpService.getAppIcon2(CACHE_ID_THUMBNAIL,
		 * applicationId, mHandler); }else{//Scrolling right now,add request to
		 * pending list if(mPendingRequest.contains(applicationId)){ return;
		 * }else if(mPendingRequest.size()>MAX_PENDING_SIZE){
		 * mPendingRequest.remove(0); } mPendingRequest.add(applicationId); }
		 */

	}

	public Drawable getThumbnail(final int position, final int id) {
		IconPair pair = IconCache.getInstance().get(id);
		Drawable icon = pair.drawable;
		if (icon == null) {
			icon = IconCache.getInstance().getDefaultIcon(this);
			addThumbnailRequest(id);
		}
		return icon;
	}

	private AbsListView.OnScrollListener scrollListener = new AbsListView.OnScrollListener() {
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
		}

		public void onScrollStateChanged(AbsListView view, int scrollState) {
			switch (scrollState) {
			case OnScrollListener.SCROLL_STATE_IDLE:
				int first = view.getFirstVisiblePosition();
				int count = view.getChildCount();

				if (first + count >= mOrgListAdapter.getCount() - 2) {
					// inflateOrgList();
				}
				mScrolling = false;
				System.gc();
				processPendingRequest();
				break;
			default:
				mScrolling = true;
			}
		}
	};

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
}
